<template>
  <scroll-view class="account-info" :style="{ height: screenHeight }">
    <div class="wrap">
      <div class="info-block">
        <div class="te">
          <div class="button" @click="toUserInfo">{{ userInfo.name }} &gt;</div>
        </div>
        <div class="te">积分 Redeem Points {{ userInfo.integral }}</div>
        <div class="te">
          <div class="button" @click="toMessage">
            <div class="span">我的消息 My Messages</div>
            <div class="red" v-if="hadUnread"></div>
            <div class="span">&gt;</div>
          </div>
        </div>
      </div>

      <div class="vip-box">
        <template v-if="!isVip">
          <div class="not-vip">
            <div class="not-text" @click="toVipInfo">
              <div class="span">立即订阅会员，享受更多优惠。</div>
              <div class="span">Subscribe to our membership for special offers.</div>
            </div>
            <div class="not-img">
              <img class="img" src="@/static/icon/not-vip.png" mode="aspectFill" alt="" />
            </div>
          </div>
        </template>
        <template v-else>
          <div class="not-vip">
            <div class="not-text">
              <div class="span">会员二维码</div>
              <div class="span">Membership QR code</div>
            </div>
            <div class="vip-img">
              <img style="width: 430rpx; height: 430rpx" :src="tempath" alt="" />

              <div class="code-canvas">
                <uQrcode
                  ref="uqrcode"
                  @complete="getTempath"
                  :start="false"
                  :auto="false"
                  canvas-id="qrcode"
                  :value="codeValue"
                />
              </div>
            </div>
            <div class="not-text">
              <div class="span">会员详情 Membership Information &gt;</div>
            </div>
          </div>
        </template>
      </div>
    </div>
  </scroll-view>
</template>

<script setup lang="ts">
import uQrcode from '@/uni_modules/Sansnn-uQRCode/components/u-qrcode/u-qrcode.vue'
import { ref, computed, defineExpose, defineProps, onUnmounted } from 'vue'
import { useStore } from 'vuex'
import { onShow } from '@dcloudio/uni-app'
import { messageUnreadCount } from '@/utils/api/message'
import { getQrCode } from '@/utils/api/user'
import { encryptDes } from '@/utils/encryption'

const store = useStore()
const props = defineProps({
  pageCurrent: {
    type: Number,
    default: 0
  }
})

let tempath = ref('')
// Refs
const uqrcode = ref<InstanceType<typeof uQrcode> | null>(null)
const hadUnread = ref(false)
const codeValue = ref('')
const userCode = ref<string | number>('')
const timeCode = ref<number | null>(null)

// Computed
const screenHeight = computed(() => {
  const statusBarHeight = store.getters['system/statusBarHeight']
  const bottomSafeArea = store.getters['system/bottomSafeArea']
  return `calc(100vh - ${statusBarHeight}px - ${bottomSafeArea}px - 90rpx - 116rpx - 126rpx)`
})

const userInfo = computed(() => store.state.user.userInfo)
const isVip = computed(() => store.getters['user/isVip'])

// Methods
const toVipInfo = () => {
  uni.navigateTo({ url: '/pages/vipInfo/vipInfo' })
}

const toMessage = () => {
  uni.navigateTo({ url: '/pages/message/message' })
}

const toUserInfo = () => {
  uni.navigateTo({ url: '/pages/userInfo/userInfo' })
}

const createCode = () => {
  const id = store.state.user.userInfo.id.toString()
  codeValue.value = `vip^${encryptDes(id)}^${encryptDes(userCode.value)}`
  uqrcode.value?.remake()
}

const getTempath = (e: { success: boolean }) => {
  if (!e.success) {
    console.error('二维码生成失败')
    return
  }

  uqrcode.value?.toTempFilePath({
    success: (res) => {
      tempath.value = res.tempFilePath // 这里赋值给模板使用的变量
    },
    fail: (err) => {
      console.error('获取临时路径失败:', err)
    }
  })
}

const getUnReadCount = async () => {
  const { code, data } = await messageUnreadCount()
  hadUnread.value = code === 200 && data > 0
}

const haveCode = async () => {
  if (uni.getStorageSync('currentTopTab') !== 0) {
    clearCodeInterval()
    return
  }

  const { code, data } = await getQrCode()
  if (code !== 200) return

  userCode.value = data
  createCode()
}

const clearCodeInterval = () => {
  if (timeCode.value) {
    clearInterval(timeCode.value)
    timeCode.value = null
  }
}

const initData = () => {
  store.dispatch('user/getUserInfo')
  getUnReadCount()
  haveCode()

  if (!timeCode.value) {
    timeCode.value = setInterval(haveCode, 9000)
  }
}

// Lifecycle
onUnmounted(clearCodeInterval)

defineExpose({
  initData,
  closeCode: clearCodeInterval
})
</script>

<style lang="scss" scoped>
@import './accountInfo.scss';
</style>
